package com.fsck.k9.accounts;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import com.fsck.k9.accounts.R;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class Export extends Activity {
	private static final int DIALOG_PROGRESS = 1;
    private int maxProgress=0;
	
	private ArrayList<Account> accounts=new ArrayList<Account>();
    private ProgressDialog mProgressDialog;
    private int mProgress;
    private Handler mProgressHandler;
	protected int currentCheckedItem;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.import_export);


        ContentResolver cr = this.getContentResolver();
		
		Uri uri=Uri.parse("content://com.fsck.k9.accountprovider/accounts");
	    final Cursor accountCursor=cr.query(uri, null, null, null, null);
		if(accountCursor!=null && accountCursor.moveToFirst())
			do
			{
				if(accountCursor.getColumnIndex("accountUuid")!=-1)
					this.accounts.add(new Account(accountCursor.getString(accountCursor.getColumnIndex("accountName")),accountCursor.getString(accountCursor.getColumnIndex("accountUuid")),accountCursor.getInt(accountCursor.getColumnIndex("accountNumber"))));
			}            
			while(accountCursor.moveToNext());

		ListView accountsList = (ListView) findViewById(R.id.accounts);
        
        accountsList.setItemsCanFocus(false);
        accountsList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        if(this.accounts.size()>0)
        {
	        accountsList.setSelection(this.accounts.size());
			
	        ArrayAdapter<Account> adapter = new ArrayAdapter<Account>(this, android.R.layout.simple_list_item_multiple_choice, (Account[]) this.accounts.toArray(new Account[1]));
	        accountsList.setAdapter(adapter);
        }
        ((Button)findViewById(R.id.doIt)).setText(R.string.export_string);

        mProgressHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (mProgress >= Export.this.maxProgress) {
                    mProgressDialog.dismiss();
                    Export.this.finish();
                } else {
                    ListView accountsList = (ListView) findViewById(R.id.accounts);
                    long ids[]=accountsList.getCheckItemIds();
                    while(Export.this.currentCheckedItem<ids.length && accountsList.isItemChecked((int)ids[Export.this.currentCheckedItem])==false)
                		Export.this.currentCheckedItem++;
                   	Account account= (Account) accountsList.getItemAtPosition((int)ids[Export.this.currentCheckedItem]);

            		File storageDir=new File(Main.STORAGE_LOCATION);
            		if(storageDir.exists()==false || storageDir.isDirectory()==false) 
            			storageDir.mkdirs();
    				Uri uri=Uri.parse("content://com.fsck.k9.accountprovider/read/"+account.getId()+"/");
    	    		ContentResolver cr = getBaseContext().getContentResolver();

    				Cursor unreadCur=cr.query(uri, null, null, null, null);
    				unreadCur.moveToFirst();
    				String xmlAccount=unreadCur.getString(unreadCur.getColumnIndex("xmlContent"));
    				try {
    					FileOutputStream fout=new FileOutputStream(Main.STORAGE_LOCATION+"/"+account.getUuid()+".xml", false);
    				    fout.write(xmlAccount.getBytes());
    				    fout.flush(); fout.close();
    				}
    				catch (IOException e)
    				{
    				    System.out.println("Exception ");

    				} 
                   	
                   	Export.this.currentCheckedItem++;
                   	mProgress++;
                    mProgressDialog.incrementProgressBy(1);
                    mProgressHandler.sendEmptyMessageDelayed(0, 100);
                }
            }
        };

        
        this.findViewById(R.id.doIt).setOnClickListener(new OnClickListener() {
    		@Override
    		public void onClick(View v) {
    			// TODO Auto-generated method stub
    			Export.this.maxProgress=0;
    			Export.this.currentCheckedItem=0;
                ListView accountsList = (ListView) findViewById(R.id.accounts);
                long ids[]=accountsList.getCheckItemIds();
                for(int pos=0; pos<ids.length;pos++)
                {
                	if(accountsList.isItemChecked((int)ids[pos]))
                		maxProgress++;
                }

                showDialog(DIALOG_PROGRESS);
                mProgress = 0;
                mProgressDialog.setProgress(0);
                mProgressHandler.sendEmptyMessage(0);
                
    		}
            });
        this.findViewById(R.id.SelectAll).setOnClickListener(new OnClickListener() {
    		@Override
    		public void onClick(View v) {
    			// TODO Auto-generated method stub
                ListView accountsList = (ListView) findViewById(R.id.accounts);
                for(int pos=0; pos<accountsList.getCount();pos++)
                	accountsList.setItemChecked(pos, true);
    		}
            });
        this.findViewById(R.id.UnselectAll).setOnClickListener(new OnClickListener() {
    		@Override
    		public void onClick(View v) {
    			// TODO Auto-generated method stub
                ListView accountsList = (ListView) findViewById(R.id.accounts);
                for(int pos=0; pos<accountsList.getCount();pos++)
                	accountsList.setItemChecked(pos, false);
    		}
            });
     }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_PROGRESS:
            mProgressDialog = new ProgressDialog(Export.this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMax(this.maxProgress);
            return mProgressDialog;
        }
		return null;
    }
 }
